<?php

namespace app\api\controller;

use app\api\model\User as UserModel;
use app\api\model\vipcard\OrderPlan as OrderPlanModel;
use app\api\model\vipcard\Order as OrderModel;
use app\common\library\MysicLog;
use think\Db;


/**
 * API控制器基类
 * Class BaseController
 * @package app\store\controller
 */
class VipSupplement extends \think\Controller
{
    // 订单模型
    public $model;

    // 当前用户信息
    protected $user;

    // 当前订单快照
    protected $orderplan;

    protected $mysicLog;
    /**
     * 构造函数
     * PaySuccess constructor.
     * @param $orderNo
     * @throws \think\exception\DbException
     */
    public function __construct($orderNo)
    {

        // 实例化订单模型 123
        $this->model = OrderModel::testGetPayDetail($orderNo);

        $this->wxappId = $this->model['wxapp_id'];

        // 获取用户信息
        $this->user = UserModel::detail($this->model['user_id']);

        // 获取订单快照
        $this->orderplan = OrderPlanModel::detail($this->model['order_id']);

        $this->mysicLog = MysicLog::instance();
    }



    /**
     * 获取订单详情
     * @return OrderModel|null
     */
    public function getOrderInfo()
    {
        return $this->model;
    }

    /**
     * 订单支付成功业务处理
     * @param int $payType 支付类型
     * @param array $payData 支付回调数据
     * @return bool
     */
    public function onPaySuccess()
    {

        try {
            $this->updatePayStatus();
        } catch(\Exception $e) {
            $this->mysicLog->error(exceptionLogFormat($e), '更新用户余额，用户等级，单条订单记录表加数据，用户积分变动明细，发放分销佣金时异常');
        }
        // 更新付款状态


    }


    /**
     * 更新付款状态
     * @param $payType
     * @param array $payData
     * @return bool
     */
    private function updatePayStatus()
    {
        $this->mysicLog->setFilename('notify/viporder');

//        $this->mysicLog->info("更新VIP订单-用户信息", $this->user->toArray());
//        $this->mysicLog->info("更新VIP订单-orderplan", $this->orderplan ?? []);

        //return $this->model->transaction(function () use ($payType, $payData) {

        // +----------------------------------------------------------------------
        // | 用户总支付的金额、充值余额、用户可用积分变更---user
        // +----------------------------------------------------------------------
        Db::name('user')->where(['user_id'=>$this->user['user_id']])->setInc('pay_money',$this->model['pay_price']);
        $this->mysicLog->info("成功", '用户总支付的金额变更');

        Db::name('user')->where(['user_id'=>$this->user['user_id']])->setInc('money',$this->orderplan['card_money']);
        $this->mysicLog->info("成功", '充值余额变更');

        Db::name('user')->where(['user_id'=>$this->user['user_id']])->setInc('points',$this->orderplan['reward_point']);
        $this->mysicLog->info("成功", '用户可用积分变更');

        // +----------------------------------------------------------------------
        // | 更新用户等级---user
        // +----------------------------------------------------------------------
        if($this->user['vip_level']<=$this->orderplan['card_id']){
            Db::name('user')->where(['user_id'=>$this->user['user_id']])->update(['vip_level'=>$this->orderplan['card_id']]);
            $this->mysicLog->info("成功", '用户等级变更');
        }

        // +----------------------------------------------------------------------
        // | 用户单条订单记录表加数据---single_order
        // +----------------------------------------------------------------------
        $orderData['amount'] = $this->model['pay_price'];
        $orderData['pay_type'] = 40;
        $orderData['wxapp_id']=$this->model['wxapp_id'];
        $orderData['user_id']=$this->user['user_id'];

        $this->singleOrder(['wxapp_id'=>$this->model['wxapp_id'],'user_id'=>$this->user['user_id']],$orderData);
        $this->mysicLog->info("成功", '用户单条订单记录表加数据成功');


        // +----------------------------------------------------------------------
        // | 用户余额变动明细加数据---user_money_log
        // +----------------------------------------------------------------------
        $money_log = [
            'user_id' => $this->user['user_id'],
            'scene'=>10,
            'money' => $this->orderplan['card_money'],
            'order_no' => $this->model['order_no'],
            'wxapp_id' => $this->orderplan['wxapp_id'],
            'create_time' => time(),
        ];
        $this->mysicLog->info($money_log, '用户余额变动数据');
        if($this->orderplan['card_money']>0){
            $money_log_status = Db::name('user_money_log')->insertGetId($money_log);
            $this->mysicLog->info($money_log_status, '用户余额变动数据结果');
        }


        // +----------------------------------------------------------------------
        // | 用户积分变动明细加数据---user_points_log
        // +----------------------------------------------------------------------
        $points_Log = [
            'user_id' => $this->user['user_id'],
            'scene'=>10,
            'value' => $this->orderplan['reward_point'],
            'order_no' => $this->model['order_no'],
            'wxapp_id' => $this->orderplan['wxapp_id'],
            'create_time' => time(),
        ];
        $this->mysicLog->info($points_Log, '用户积分变动明细数据');
        if($this->orderplan['reward_point']>0){
            $points_log_status = Db::name('user_points_log')->insertGetId($points_Log);
            $this->mysicLog->info($points_log_status, '用户积分变动数据结果');
        }


        // +----------------------------------------------------------------------
        // | 发放分销佣金
        // +----------------------------------------------------------------------

        //DealerOrderModel::grantVipMoney($this->model,30,20);
        $this->grantMoney($this->model);
        return true;
        //});
    }



    /**
     * 发放储值卡分销订单佣金
     * @param array|\think\Model $order 订单详情
     * @param int $orderType 订单类型
     * @return bool|false|int
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function grantMoney($data)
    {
        $this->mysicLog->setFilename('notify/viporder');
        $this->mysicLog->info("开始", '发放储值卡分销订单佣金');
        // 分销订单详情
        $dealerOrder = Db::name('dealer_order')->where(['order_id'=>$data['order_id'],'is_settled'=>0,'order_type'=>30])->find();
        if(!$dealerOrder){
            $this->mysicLog->info("无分销订单", '无分销订单');
            return false;
        }
        $this->mysicLog->info($dealerOrder, '发放储值卡分销订单佣金分销订单详情');

        // +----------------------------------------------------------------------
        // | dealer_order表更新数据----分销商订单记录表
        // +----------------------------------------------------------------------
        Db::name('dealer_order')->where(['order_id'=>$data['order_id'],'order_type'=>30])->update(['is_settled' => 1,'settle_time' => time()]);

        $this->mysicLog->info($dealerOrder['first_money'], '分销商用户记录表dealer_user，分销佣金');
        $this->mysicLog->info($dealerOrder['first_user_id'], '分销商用户记录表dealer_user，上级id');

        if($dealerOrder['first_user_id']>0 && $dealerOrder['first_money']>0){
            // +----------------------------------------------------------------------
            // | dealer_user表更新数据----分销商用户记录表
            // +----------------------------------------------------------------------
            Db::name('dealer_user')
                ->where(['user_id'=>$dealerOrder['first_user_id']])
                ->setInc('money', $dealerOrder['first_money']);


            // +----------------------------------------------------------------------
            // | dealer_capital表加数据----分销商资金明细表
            // +----------------------------------------------------------------------
            $capitalData = [
                'user_id'=>$dealerOrder['first_user_id'],
                'flow_type'=>20,
                'money'=>$dealerOrder['first_money'],
                'wxapp_id'=>$dealerOrder['wxapp_id'],
                'create_time'=>time(),
                'update_time'=>time(),
            ];

            $this->mysicLog->info($capitalData, '分销商资金明细表数据');
            $dealer_capital_id = Db::name('dealer_capital')->insertGetId($capitalData);

            $this->mysicLog->info($dealer_capital_id, '获取分销商资金明细表ID');
        }

    }




    /**
     * 用户单条订单记录表
     * @param int $payType 支付类型
     * @param array $payData 支付回调数据
     * @return bool
     */

    public  function singleOrder($where,$data){
        //分销商表
        $flag = Db::name('single_order')->where($where)->find();
        if(!$flag){
            $single_data = [
                'amount'=>$data['amount'],
                'wxapp_id'=>$data['wxapp_id'],
                'pay_type'=>$data['pay_type'],
                'user_id'=>$data['user_id'],
                'create_time'=>time(),
                'update_time'=>time(),
            ];
            Db::name('single_order')->insertGetId($single_data);
        }else{
            if($flag['amount']<$data['amount']){
                $data['update_time'] = time();
                Db::name('single_order')->where($where)->update($data);
            }
        }
    }

}
